<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ArticlePregCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'article:preg';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $htmlContent = file_get_contents('public/test.html');
        // 下载并替换图片 URL
        $htmlContent = preg_replace_callback('/(<img[^>]+src=")(https:\/\/mmbiz\.qpic\.cn\/mmbiz_[^"]+)("[^>]*>)/i', function ($matches) {
            $originalUrl = $matches[2];
            $localUrl = $this->downloadImage($originalUrl);

            return $matches[1] . $localUrl . $matches[3];
        }, $htmlContent);
        file_put_contents('public/test2.html', $htmlContent);
        return 0;
    }


    public function downloadImage($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $imageData = curl_exec($ch);
        curl_close($ch);

        if ($imageData) {
            // 判断图片类型
            $isSvg = strpos($url, '?wx_fmt=svg') !== false;
            $extension = $isSvg ? '.svg' : '.jpg'; // 默认为 jpg，可以根据实际情况调整
            $filename = md5($url) . $extension; // 可以根据实际图片格式调整扩展名
            $uploadDir = __DIR__ . '/../../../public/uploads/wechat/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }


            file_put_contents($uploadDir . $filename, $imageData);
            return 'https://manage.lanzhankeji.com/uploads/wechat/' . $filename; // 替换为你的域名
        }
        return $url;
    }
}
